//
//  SQLiteHelper.m
//  MoneyLog
//
//  Created by Max on 11-1-22.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SQLiteHelper.h"

#import "Record.h"
#import "RecordWrapper.h"
#import "KindWrapper.h"
#import "MyCategory.h"

@implementation SQLiteHelper

-(id) init{
    
	if (self ==[super init]) {
        
    } 	
    
    return self;
}

//初始化数据库
+(FMDatabase *) openDatabase{
	BOOL        success;
	NSError     *error;
    
    FMDatabase *fmdb;
    
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"moneylog.db"];
	
	success = [fileManager fileExistsAtPath:writableDBPath];
	if(!success){
        
		NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"moneylog.db"];
		success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
		if(!success){
            
			 success = NO;
		}
        else{
            
            success = YES;
            fmdb = [[FMDatabase databaseWithPath:writableDBPath] retain];
            if ([fmdb open]) {
                
                [fmdb setShouldCacheStatements:YES];
            }
            else{
                
                success = NO;
            }
        }
	}
    else
    {
		fmdb = [[FMDatabase databaseWithPath:writableDBPath] retain];
		if ([fmdb open]) {
            
			[fmdb setShouldCacheStatements:YES];
		}
        else{
            
			success = NO;
		}
	}
	
	return fmdb;
}

//获取数据库访问对象
+ (FMDatabase *) getDatabase{
    static FMDatabase *fmdb;
    
    if (fmdb == nil) {
        fmdb = [self openDatabase];
    }
        
    return fmdb;
}

//重置
+(BOOL) resetDatabase{
 
    FMDatabase *fmdb = [self getDatabase];
    
    if (![fmdb close]) {
        return NO;
    }
    
    if (![fmdb open]) {
        return NO;
    }
    
	return YES;
}

//关闭数据库
+ (void) closeDatabase{
    FMDatabase *fmdb = [self getDatabase];
    
	[fmdb close];
}

#pragma mark  - *sql operation
// SELECT
+ (id)query:(NSString*)sql,... { 
    
	FMResultSet *resultSet = [[[FMResultSet alloc] init] autorelease]; 
    FMDatabase *fmdb =[self getDatabase];
    
	resultSet=[fmdb executeQuery:sql];
	
	return resultSet;
}

// execute
+ (BOOL)executeSql:(NSString *)sql,...{
    
    FMDatabase *fmdb = [self getDatabase];
    
	[fmdb executeUpdate:sql];
	if ([fmdb hadError]) {
		NSLog(@"Err %d: %@", [fmdb lastErrorCode], [fmdb lastErrorMessage]);
		return NO;
	}
	
	return YES;
}

- (void)dealloc {
	[super dealloc];
}

@end
